(load "~/quicklisp/setup.lisp")
;; (push :hunchentoot-no-ssl *features*)

(ql:quickload '(hunchentoot cl-json cl-prevalence))
;;我们为 people 新增了一个 id 字段，为方便流行持久化系统使用
(defclass people()
  ((id :reader id
       :initarg :id)
   (name :accessor name
         :initarg :name)
   (language :accessor language
             :initarg :language)
   (words :accessor words
        :initarg :words)))
;;初始化系统
(defvar *p-system* (cl-prevalence:make-prevalence-system #p"./p-system/"))
;;创建计数器
(or (> (length (cl-prevalence:find-all-objects *p-system* 'people)) 0)
    (cl-prevalence:tx-create-id-counter *p-system*))
(hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 4242))
;;创建 people 对象至流行持久化系统
(defun make-people (name)
  (cl-prevalence:tx-create-object
   *p-system*
   'people
   `((name ,name)
     (language ,"中文")
     (words ,(format nil "~a，你尽管捅死我吧，生又何哀，死又何苦，等你明白了舍生取义，后果可想而知。" name))))
  (cl-prevalence:snapshot *p-system*) 
  (cl-prevalence:find-all-objects *p-system* 'people)
  )
;;根据参数构建一个 people 对象，转换成 JSON 然后返回
(hunchentoot:define-easy-handler (say-you :uri "/you") (name)
  (setf (hunchentoot:content-type*) "application/json")
  (json:encode-json-to-string
   (make-people name)))
;;获取流行持久化系统内所有的 people 实例
(hunchentoot:define-easy-handler (people :uri "/people") ()
  (setf (hunchentoot:content-type*) "application/json")
  (json:encode-json-to-string
   (cl-prevalence:find-all-objects *p-system* 'people)))
